
package com.mengmeizi.util;

import android.os.Handler;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailTool {

    public static void sendMail(Handler handler, String subject, String content) throws MessagingException {
        // Properties props = new Properties();
        // props.put("mail.smtp.host", "mail.sina.cn");// 存储发送邮件服务器的信息
        // props.put("mail.smtp.auth", "true");// 同时通过验证
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", "smtp.gmail.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        // 基本的邮件会话
        Session session = Session.getInstance(props);
        session.setDebug(true);// 设置调试标志
        // 构造信息体
        MimeMessage message = new MimeMessage(session);

        // 发件地址
        Address fromAddress = null;
        fromAddress = new InternetAddress("appcontact2012@gmail.com");

        message.setFrom(fromAddress);

        // 收件地址
        Address toAddress = new InternetAddress("appcontact2012@gmail.com");
        message.addRecipient(Message.RecipientType.TO, toAddress);

        // 解析邮件内容
        message.setSubject(subject);// 设置信件的标题
        message.setText(content);// 设置信件内容
        message.saveChanges(); // implicit with send()//存储信息

        // send e-mail message
        Transport transport = null;
        transport = session.getTransport("smtp");
        transport.connect("smtp.gmail.com", "zhengdianstudio@gmail.com", "zhengdianstudio");

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        handler.sendEmptyMessage(Const.SEND_MAIL_SUCCESS);
    }

}
